package dfs;

/**
 * @author wcj
 * @Date 2021/7/6 19:09
 * @Version 1.0
 */
public class PathSumFirst {

    /**
     * 判断二叉树中有没有根节点到叶子节点的权值和为target的路径
     * 深搜
     * ①递归方法的设计：dfs(TreeNode root,int target)其中root表示当前访问到的节点，target表示目前剩余的值
     * ②递归出口：root == null，截止；root.left == null && root.right == null && target == root.val，截止
     * ③递归组合方式：前序遍历
     *
     * @param root
     * @param target
     * @return
     */
    public static boolean pathSum(TreeNode root, int target) {
        return dfs(root, target);
    }

    public static boolean dfs(TreeNode root, int target) {
        if (root == null) {
            return false;
        }
        if (root.left == null && root.right == null && target == root.val) {
            return true;
        }
        boolean left = dfs(root.left, target - root.val);
        boolean right = dfs(root.right, target - root.val);
        return left || right;
    }

}

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;

    public TreeNode(int val) {
        this.val = val;
    }
}
